import { defineStore } from "pinia";
import api from '@/api/getToken'

export const useRouteMenu = defineStore("menu", {
  persist: true, //开启数据持久化
  //数据持久化参数
  persist: [
    {
      key: "menu",
      storage: localStorage,
      paths: ["menu"],
    },
    {
      key: "lang",
      storage: localStorage,
      paths: ["lang"],
    },
    {
      key: "theme",
      storage: localStorage,
      paths: ["theme"],
    },
    {
      key: "bread",
      storage: localStorage,
      paths: ["bread"],
    },
    {
      key: "openmenu",
      storage: localStorage,
      paths: ["openmenu"],
    }
  ],
  state: () => {
    return {
      menu: [], // 后台菜单
      lang: 'zhCn', // 中英文切换
      theme: 'light', // 主题
      bread: [], // 面包屑
      openmenu: 1 // 当前展开的菜单
    }
  },
  actions: {
    setMenu(theme) {
      return new Promise((resolve, reject) => {
        api.getMenu({ lang: this.lang }).then(menuRes => {
          if(menuRes) {
            resolve(menuRes.data)
            this.menu = menuRes.data
            this.bread = this.bread.length === 0 ? [this.menu[0]]: this.bread;
            this.setBread(this.menu)
          }
        })
      })
    },
    // 中英文切换面包屑重置
    setBread(arr) {
      let menus = []
      const fn = (data) => {
        data.forEach(item => {
          if(item.children) fn(item.children)
          else menus.push(item)
        })
      }
      fn(this.menu)
      let ids = this.bread.map(item => item.id)
      this.bread = menus.filter(item => ids.includes(item.id))
    }
  },
  getters: {},
});
